<?php
/*
 * -------------------------
 * str
 * -------------------------
*/
//截断字符串
function str_cut($str, $len, $ext = '...', $encode = 'utf8')
{
  if (empty($str)) return $str;
  if (mb_strwidth($str, $encode) > $len) {
    $str = mb_strimwidth($str, 0, $len, $ext, $encode);
  }

  return $str;
}
function str_trim($str, $letter = ' ')
{
  return trim($str, $letter);
}
function str_ltrim($str, $letter = ',')
{
  return ltrim($str, $letter);
}
function str_rtrim($str, $letter = ',')
{
  return rtrim($str, $letter);
}
/**
 * 按符号截取字符串的指定部分
 * @param string $str 需要截取的字符串
 * @param string $sign 需要截取的符号
 * @param int $number 数组索引
 * @return string 返回截取的内容
 */
function str_part($str, $sign, $number = 0)
{
  $array = explode($sign, $str);
  $length = count($array);

  if ($number < 0) {
    $new_array = array_reverse($array);
    $abs_number = abs($number);
    if ($abs_number <= $length) {
      return $new_array[$abs_number - 1];
    }
    return 'error';
  }

  if ($number < $length) {
    return $array[$number];
  }
}
//返回可安全执行的SQL,带html格式
function str_isafe($str)
{
  if (is_null($str) || $str == '') return $str;

  // 使用mysqli_real_escape_string对字符串进行转义，确保它不会造成SQL注入
  if (!ini_get('magic_quotes_gpc')) $str = addslashes($str);

  // if (function_exists('mysqli_real_escape_string')) $str = mysqli_real_escape_string($GLOBALS['db'], $str);

  return trim($str);
  // $tmp = array("select ", "insert ", "update ", "delete ", " and", "drop table", "script", "*", "%", "eval", "'", "\"", "or =", "\r", "\n", "\t");
  // $tmp_re = array('sel&#101;ct ', 'ins&#101;rt ', 'up&#100;ate ', 'del&#101;te ', ' an&#100;', 'dro&#112; table', '&#115;cript', '&#42;', '&#37;', '$#101;val', "&acute;", "&quot;", 'or&nbsp;=', '', '', '');
  // return str_replace($tmp, $tmp_re, trim(!ini_get('magic_quotes_gpc') ? addslashes($str) : $str));
}
//返回可安全执行的SQL,不带html格式
function str_safe($str)
{
  if (is_null($str) || $str == '') return $str;
  $str = str_isafe($str);
  return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');

  // return str_isafe(htmlspecialchars(!ini_get('magic_quotes_gpc') ? addslashes($str) : $str));
}
//返回无空格,tab,html的字串
function str_text($str, $ext = 0)
{
  if (is_null($str) || $str == '') return $str;

  $str = strip_tags(str_safe($str));

  switch ($ext) {
    case 1:
      $filter = array("\r\n", "\r", "\n", " ", "　", chr(34), chr(13), " ", "&nbsp;", "&emsp;");
      break;
    case 2:
      $filter = array(" ", "　", chr(34));
      break;
    case 9:
      $filter = false;
      break;
    default:
      $filter = array("\r\n", "\r", "\n", " ", "　", chr(34), chr(13), "  ");
      break;
  }

  return $filter ? str_replace($filter, '', $str) : $str;
  // return $filter ? str_replace($filter, '', strip_tags(str_isafe($str))) : strip_tags(str_isafe($str));
}
function array_str($arr, $split = ',')
{
  if (is_array($arr) && !empty($arr)) {
    $str = implode($split, $arr);
  }

  return rtrim($str, $split);
}
function str_array($str, $split = ',')
{
  if (strpos($str, $split) === false) {
    return [$str];
  }

  return explode($split, rtrim($str, $split));
}
//高亮显示
function high_light($t0, $t1)
{
  return str_replace($t1, '<span class="highlight">' . $t1 . '</span>', $t0);
}
// 随机码
function str_rand($len = 6)
{
  $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  // characters to build the password from
  mt_srand((float) microtime() * 1000000 * getmypid());
  // seed the random number generater (must be done)
  $tmp_str = '';
  while (strlen($tmp_str) < $len) {
    $tmp_str .= substr($chars, mt_rand() % strlen($chars), 1);
  }
  return $tmp_str;
}
// 32位非0整数
function str_code($len = 32)
{
  $chars = '123456789';
  // characters to build the password from
  mt_srand((float) microtime() * 1000000 * getmypid());
  // seed the random number generater (must be done)
  $tmp_str = '';
  while (strlen($tmp_str) < $len) {
    $tmp_str .= substr($chars, mt_rand() % strlen($chars), 1);
  }
  return $tmp_str;
}

/**
 * 10年一循环的16位唯一字串
 * 注意服务器环境时间依赖
 */
function str_unique()
{
  $y_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
  return $y_code[intval(date('y')) % 10] . strtoupper(dechex(date('m'))) . date('d') . substr(gmtime(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
  // return $y_code[intval(date('y')) % 10] . date('m') . date('d') . substr(gmtime(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
}
// 掩码处理（默认为手机号处理）
// $t1 从第几位开始 $t2 到第几位结束
// $t3 倒数几位
// 如银行卡号：0,4,3 得出6222************847
function str_mask($t0, $t1 = 0, $t2 = 3, $t3 = 4)
{
  if (extension_loaded('mbstring')) {
    $strlen = mb_strlen($t0);
    $str_mid = '';
    $str_pre = mb_substr($t0, $t1, $t2);
    $str_suf = $t3 ? mb_substr(
      $t0,
      -$t3
    ) : '';
    for ($i = 0; $i < $strlen - ($t2 + $t3); $i++) {
      $str_mid .= '*';
    }
    return $str_pre . $str_mid . $str_suf;
  }

  $strlen = strlen($t0);
  $str_mid = '';
  $str_pre = substr($t0, $t1, $t2);
  $str_suf = $t3 ? substr($t0, -$t3) : '';
  for ($i = 0; $i < $strlen - ($t2 + $t3); $i++) {
    $str_mid .= '*';
  }
  return $str_pre . $str_mid . $str_suf;
}
function color_rand()
{
  return '#' . dechex(rand(0, 16777215));
}
function unicode_chinese($str)
{
  return preg_replace_callback(
    "#\\\u([0-9a-f]{4})#i",
    function ($r) {
      return iconv('UCS-2BE', 'UTF-8', pack('H4', $r[1]));
    },
    $str
  );
}
function alph_num($char)
{
  $char = strtolower($char);
  $array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
  $len = strlen($char);
  $sum = '';
  for ($i = 0; $i < $len; $i++) {
    $index = array_search($char[$i], $array);
    $sum += ($index + 1) * pow(26, $len - $i - 1);
  }
  return $sum;
}
function num_alph($n)
{
  $n++;
  $array = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e', 6 => 'f', 7 => 'g', 8 => 'h', 9 => 'i', 10 => 'j', 11 => 'k', 12 => 'l', 13 => 'm', 14 => 'n', 15 => 'o', 16 => 'p', 17 => 'q', 18 => 'r', 19 => 's', 20 => 't', 21 => 'u', 22 => 'v', 23 => 'w', 24 => 'x', 25 => 'y', 26 => 'z');
  if ($n <= 26) {
    return strtoupper($array[$n]);
  }

  if ($n % 26 == 0) {
    return strtoupper($array[floor(($n - 1) / 26)] . $array[26]);
  }

  return strtoupper($array[floor($n / 26)] . $array[$n % 26]);
}
function iif($a, $b)
{
  return $a ?: $b;
  // return !empty($a) ? $a : $b;
}
function is_in_str($str, $str_array, $spl = ',')
{
  if (empty($str_array)) {
    return false;
  }

  $arr = str_array($str_array);

  if (in_array($str, $arr)) {
    return true;
  }

  return false;
}

function set_cookie($name, $value, $expires, $path = '/', $safety = false, $httponly = true)
{
  $path = empty($path) ? '/' : $path;
  return setcookie($name, $value, $expires, $path, "", $safety, $httponly);
}

function get_post_filter($key, $val)
{
  if (is_array($val)) {
    return array_str($val);
  }

  if (is_int($val)) {
    return intval($val);
  }

  if (
    strpos($key, '_date') !== false ||
    strpos($key, '_sdate') !== false ||
    strpos($key, '_edate') !== false
  ) {
    return empty($val) ? 0 : local_strtotime($val);
  }

  return $val;
}

function get_post_inc($inc = [], $is_safe = true)
{
  $data = array();

  foreach ($_POST as $key => $val) {
    if (!in_array($key, $inc) && (is_null($val) || $val == '')) {
      continue;
    }

    if ($val == '') {
      \alert_back($GLOBALS['lang']['data']['empty']);
    }

    $data[$key] = get_post_filter($key, $val);
    $data[$key] = $is_safe ? str_isafe($data[$key]) : $data[$key];
  }

  return $data;
}

function get_post($esc = [], $is_safe = true)
{
  $data = array();

  foreach ($_POST as $key => $val) {
    if (in_array($key, $esc) && (is_null($val) || '' == $val)) {
      continue;
    }

    if (!in_array($key, $esc) && $val == '') {
      \alert_back($GLOBALS['lang']['data']['empty']);
    }

    $data[$key] = get_post_filter($key, $val);
    $data[$key] = $is_safe ? str_isafe($data[$key]) : $data[$key];
  }

  return $data;
}


function cms($k, $v = NULL)
{
  if (!empty($k) && $v === NULL) {
    return @$GLOBALS['cms'][$k];
  }

  if (!empty($k) && $v !== NULL) {
    $GLOBALS['cms'][$k] = $v;
    return;
  }

  return false;
}

function hex_bin($var)
{
  return pack("H*", $var);
}
function mysql_installed()
{
  return function_exists("mysql_connect") ? true : false;
}
function mysqli_installed()
{
  return function_exists("mysqli_connect") ? true : false;
}

function check_GD()
{
  $arr = gd_info();
  return version_compare('2.0.28', $arr['GD Version'], ">") && $arr['PNG Support'];
  /*
  if (version_compare('2.0.28', $arr['GD Version'], ">") && $arr['PNG Support']) {
    return true;
  } else {
    return false;
  }
  */
}

// addon
function get_addon()
{
  $addons = stripslashes_deep(file_get('json', 'addon'));
  if (!empty($addons)) {
    $res = array();
    foreach ($addons as $val) {
      $res[$val['a_func']] = $val['a_name'];
    }
    return $res;
  }

  return false;
}

// 短时间内次数限制
function times_limit($login_count, $var, $times = 5)
{
  $login_count = str_safe($login_count);
  $var = str_safe($var);
  $times = intval($times);
  $time = gmtime();

  if (!isset($_SESSION[$login_count])) {
    $_SESSION[$login_count] = 0;
  }
  if (!isset($_SESSION[$var])) {
    $_SESSION[$var] = $time;
  }
  $_SESSION[$login_count]++;
  if (($_SESSION[$login_count] > $times) && (($time - $_SESSION[$var]) <= COOKIE_TIMEOUT)) {
    $_SESSION[$var] = $time;
    alert_back("短时间内请不要重复操作!");
  }
  if ($time - $_SESSION[$var] > COOKIE_TIMEOUT) {
    $_SESSION[$login_count] = 0;
  }
}


// 调试
function dump($var, $echo = true, $label = null, $strict = true)
{
  $label = ($label === null) ? '' : rtrim($label) . ' ';
  if (!$strict) {
    if (ini_get('html_errors')) {
      $output = print_r($var, true);
      $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
    } else {
      $output = $label . print_r($var, true);
    }
  } else {
    @ob_start();
    var_dump($var);
    $output = ob_get_clean();
    if (!extension_loaded('xdebug')) {
      $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
      $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
    }
  }
  if ($echo) {
    echo $output;
    return null;
  } else {
    return $output;
  }
}

function dd($var = '', $echo = true, $label = null, $strict = true)
{
  dump($var, $echo = true, $label = null, $strict = true);
  exit();
}

function gzip_enabled()
{
  static $enabled_gzip = NULL;
  if ($enabled_gzip === NULL) {
    $enabled_gzip = function_exists('ob_gzhandler');
  }
  return $enabled_gzip;
}

//获得查询时间和次数
function assign_query_info()
{
  if ($GLOBALS['db']->queryTime == '') {
    $query_time = 0;
  } else {
    if (PHP_VERSION >= '5.0.0') {
      $query_time = number_format(microtime(true) - $GLOBALS['db']->queryTime, 6);
    } else {
      list($now_usec, $now_sec) = explode(' ', microtime());
      list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime);
      $query_time = number_format($now_sec - $start_sec + ($now_usec - $start_usec), 6);
    }
  }
  // $query_info = '共处理 ' . $GLOBALS['db']->queryCount . ' 条查询, 用时 ' . $query_time . ' 秒';
  $query_info = '用时 ' . $query_time . ' 秒';
  //内存占用情况
  if (function_exists('memory_get_usage')) {
    $memory_info = '内存占用 ' . memory_get_usage() / 1048576 . ' m';
  }
  //是否启用了 gzip
  $gzip = gzip_enabled() ? '支持' : '不支持';
  return $query_info . '&nbsp;&nbsp;' . $memory_info . '&nbsp;&nbsp;gzip:' . $gzip;
}

function stripslashes_deep($arr)
{
  $res = array();
  foreach ($arr as $key => $val) {
    if (is_array($val)) {
      $res[$key] = stripslashes_deep($val);
    } else {
      $res[$key] = htmlspecialchars_decode(stripslashes($val));
    }
  }
  return $res;

  // return is_array($sth) ? array_map('stripslashes_deep', $sth) : stripslashes($sth);
}

function addslashes_deep($arr)
{
  $res = array();
  foreach ($arr as $key => $val) {
    if (is_array($val)) {
      $res[$key] = addslashes_deep($val);
    } else {
      $res[$key] = addslashes($val);
    }
  }
  return $res;
}

/*
 * -------------------------
 * 废弃函数处理
 * -------------------------
*/
if (!function_exists('ereg')) {
  function ereg($pattern, $subject, &$matches = NULL)
  {
    return preg_match('/' . $pattern . '/', $subject, $matches);
  }
}
if (!function_exists('eregi')) {
  function eregi($pattern, $subject, &$matches = NULL)
  {
    return preg_match('/' . $pattern . '/i', $subject, $matches);
  }
}
if (!function_exists('ereg_replace')) {
  function ereg_replace($pattern, $replacement, $string)
  {
    return preg_replace('/' . $pattern . '/', $replacement, $string);
  }
}
if (!function_exists('eregi_replace')) {
  function eregi_replace($pattern, $replacement, $string)
  {
    return preg_replace('/' . $pattern . '/i', $replacement, $string);
  }
}
if (!function_exists('split')) {
  function split($pattern, $subject, $limit = -1)
  {
    return preg_split('/' . $pattern . '/', $subject, $limit);
  }
}
if (!function_exists('spliti')) {
  function spliti($pattern, $subject, $limit = -1)
  {
    return preg_split('/' . $pattern . '/i', $subject, $limit);
  }
}
